package org.cqut.framework.security.service;

import com.alibaba.fastjson.JSONObject;
import org.cqut.framework.security.entity.SysUserDetails;
import org.cqut.system.user.domain.SysRole;
import org.cqut.system.user.domain.SysUser;
import org.cqut.system.user.domain.SysUserRole;
import org.cqut.system.user.service.SysUserRoleService;
import org.cqut.system.user.service.SysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @author XiAoXu
 * @date 2021/10/5 23:13
 * @description 用户名:openId 密码:appId 自动注册为普通用户
 */
@Service
public class SysUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 通过用户名查询信息
     *
     * @param username 用户名
     * @return 用户详细信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.findUserByUserName(username);
        SysUserDetails sysUserDetails = new SysUserDetails();
        BeanUtils.copyProperties(sysUser, sysUserDetails);

        // 角色集合
        Set<GrantedAuthority> authorities = new HashSet<>();

        List<SysRole> roleList = sysUserService.findRoleByUserId(sysUserDetails.getId());
        roleList.forEach(role -> {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        });
        sysUserDetails.setAuthorities(authorities);
        return sysUserDetails;
    }
}
